package com.example.demo.service;


import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: 宇宙第一帅
 * @Date: 2019/3/26 17:25
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Integer insert(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        User save = userRepository.save(user);
        if (save != null) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public Integer delete(String id) {
        try{
        User byid = userRepository.findById(id).get();
        if(byid == null){
            return 2;
        }
        userRepository.deleteById(id);
        return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer update(User user) {
        try{
            User userby = userRepository.findById(user.getId()).get();
            if(userby == null){
                return 2;
            }
            userRepository.save(user);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
        return null;
        }
    }

    @Override
    public List<User> select() {

        return userRepository.findAll();
    }

    @Override
    public User idselect(String id) {
        User user = userRepository.findById(id).get();
        return user;
    }

    @Override
    public List<User> nameselect(String username) {
        List<User> user =  userRepository.findByAndUsername(username);

        return user;
    }

    @Override
    public Integer login(String username, String password) {
        try {
            List<User> byAndUsername = userRepository.findByAndUsername(username);
            if (byAndUsername != null && !byAndUsername.isEmpty()){
                User user = byAndUsername.get(0);
                if (user.getPassword().equals(password)){
                    return 1;
                }else {
                    return 2;
                }
            }else {

                return 3;
            }
        }catch (Exception e){
            e.printStackTrace();
            return 2;
        }

    }
}
